package com.lds.config.center.server.mcp.server;

import com.lds.config.center.common.model.env.request.EnvBaseListRequest;
import com.lds.config.center.common.model.env.response.EnvBaseListResponse;
import com.lds.config.center.common.model.env.response.EnvBaseResponse;
import com.lds.config.center.remote.client.server.EnvRemoteClient;
import com.lds.config.center.server.mcp.model.GetEnvMcpRequest;
import com.lds.config.center.server.mcp.model.business.GetEnvMcpResponse;
import com.lds.management.center.common.model.dto.ResultDTO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class DefaultEnvMcpServer implements EnvMcpServer {
    private final EnvRemoteClient envRemoteClient;
    
    @Tool(name = "getEnv", description = "根据环境名称获取环境信息。例如：DEV")
    @Override
    public ResultDTO<GetEnvMcpResponse> getEnv(GetEnvMcpRequest request) {
        ResultDTO<EnvBaseListResponse> resultDTO = envRemoteClient.listEnv(EnvBaseListRequest.builder().name(request.getEnvName()).build());
        if (!ResultDTO.isSuccess(resultDTO)) return ResultDTO.fail(resultDTO.getCode(), resultDTO.getMessage());
        return ResultDTO.success(buildEnvMcpResponse(resultDTO.getData()));
    }
    
    private GetEnvMcpResponse buildEnvMcpResponse(EnvBaseListResponse envBaseListResponse) {
        if (Objects.isNull(envBaseListResponse)) return null;
        List<EnvBaseResponse> envs = envBaseListResponse.getEnvs();
        if (CollectionUtils.isEmpty(envs)) return null;
    
        EnvBaseResponse env = envs.get(0);
        return GetEnvMcpResponse.builder()
                .id(env.getId())
                .name(env.getName())
                .desc(env.getDesc())
                .createTime(env.getCreateTime())
                .build();
    }
}
